package com.xiaodou.mjf.web.xface.product.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.xiaodou.mjf.application.content.service.AdvertService;
import com.xiaodou.mjf.application.content.service.BannerService;
import com.xiaodou.mjf.application.core.service.FinancingAttributeService;
import com.xiaodou.mjf.application.core.service.FinancingService;
import com.xiaodou.mjf.application.core.service.FinancingStatisticsService;
import com.xiaodou.mjf.entity.core.Financing;
import com.xiaodou.mjf.entity.core.FinancingAttribute;
import com.xiaodou.mjf.entity.core.FinancingStatistics;
import com.xiaodou.mjf.infrastructure.common.controller.ApiController;
import com.xiaodou.mjf.infrastructure.common.utils.StringUtils;
import com.xiaodou.mjf.web.xface.common.API;
import com.xiaodou.mjf.web.xface.common.ResultCode;
import com.xiaodou.mjf.web.xface.product.domain.MeiLiProduct;

/**
 * 美丽理财产品列表查询
 * Created by Rocky on 2/26/15.
 */
@RestController
@RequestMapping("v1/product/meili")
public class MeiLiProductController extends ApiController{
	
	@Resource
	BannerService bannerService;
	
	@Resource
	FinancingService financingService;
	
	@Resource
	FinancingStatisticsService financingStatisticsService;
	
	@Resource
	AdvertService advertService; 
	
	@Resource
	FinancingAttributeService  financingAttributeService;
	
	
	
	
	/**
	 * @param start 产品列表起始位置
	 * @param row 分页显示行数
	 * 
	 * */
    @RequestMapping("")
    public Map<String,Object> list(Integer start,Integer row){

    	Map<String,Object> result =  success();
    	
        if(start == null || start < 0){
            start = 0;
        }

        if(row == null){
            row = 20;
        }

		/**
		 * 产品Icon地址 icon 产品的头像 产品编号 id 产品名称 name 产品金额 amount 返还期限 term 剩余数量
		 * count 截止日期 expiry_time
		 * */
        List<MeiLiProduct> meiLiProducts0 = new ArrayList<MeiLiProduct>();
        List<MeiLiProduct> meiLiProducts1 = new ArrayList<MeiLiProduct>();
    	
        Financing  parmFinancing = new  Financing ();
    	parmFinancing.setStart(start);
    	parmFinancing.setLimit(row);
    	parmFinancing.setType(Financing.TYPE_MEILI);
        parmFinancing.setStatus(Financing.NORMAL);
//        parmFinancing.setCount(0);

        
    	Page<Financing> page = financingService.page(parmFinancing);
    	
		List<Financing> financings = page.getContent();
		
		String imageServer = API.getImageServer();
    	
		for(Financing financing:financings){
    		 //从financingStatistics表中找到剩余数量count			
			FinancingStatistics fs = financingStatisticsService.findByfinanceId(financing.getId());
			FinancingAttribute fa =financingAttributeService.get(financing.getId());
			//剩余数量
    		int count = fs.getResidualCount();
    		//美丽产品过滤剩余数量为0的记录
			if(fs == null || fa == null||count==0){
				continue;
			}			
    		//返还金额
			double refundAmount = fa.getRefundAmount();
			
			//0 为抢购中 1为售罄			
			if(Financing.INVEST_STATUS_SALE.equals(financing.getInvestStatus())){
				meiLiProducts0.add(new MeiLiProduct(financing.getId(),imageServer + financing.getIcon(),financing.getTitle(),financing.getAmount(),financing.getTerm(),count,financing.getEndTime(),refundAmount));	 
			}else if(Financing.INVEST_STATUS_FULL_SCALE.equals(financing.getInvestStatus())){
				meiLiProducts1.add(new MeiLiProduct(financing.getId(),imageServer + financing.getIcon(),financing.getTitle(),financing.getAmount(),financing.getTerm(),count,financing.getEndTime(),refundAmount));
			}
    		     		 
    	 }
    	 
        result.put("sell", meiLiProducts0);
        result.put("sell_out", meiLiProducts1);
        return result;
    }
    /**
     * 美丽理财产品详情查询
     * @param id 产品编号
     * */
    @RequestMapping("{id}")
    public Map<String,Object> get(@PathVariable String id){
    	Map<String,Object> result =  success();
    	if(StringUtils.isBlank(id)){
     	   return failure(ResultCode.MISSING_PARAMS);
        }
    	/**advert表*/
//    	//产品广告的链接	adverts  
//    	List<String>  adverts = new ArrayList<String>();
//    	List<Advert> advertsMap<String,Object> result = advertService.findByfinanceId(id);
//    	for(Advert advert:advertsResult){
//    		 String url = (advert.getUrl());
//    		 adverts.add(url);    		
//    	}
//    	result.put("items",adverts);
    	/**financing_statistics*/
    	//剩余数量	count
//    	FinancingStatistics financingStatistics =financingStatisticsService.findByfinanceId(id);
//    	result.put("count","0");
//    	if(financingStatistics!=null){
//    		result.put("count",financingStatistics.getCount());
//    	}    	
    	/**financing 表profit_type，term，amount，end_time*/
    	//投资金额	amount
    	//投资期限	term
    	//收益方式	profit_type 

    	Financing financing =financingService.get(id);
    	FinancingAttribute financingAttribute = financingAttributeService.get(id) ;

		if (financing == null || financingAttribute == null) {
			return failure(ResultCode.MEILI_RECORD_NOT_EXIST);
		}
		if(Financing.INVEST_STATUS_SALE.equals(financing.getInvestStatus())){
			result.put("status", Financing.INVEST_STATUS_SALE); 
		}else if(Financing.INVEST_STATUS_FULL_SCALE.equals(financing.getInvestStatus())){
			result.put("status", Financing.INVEST_STATUS_FULL_SCALE); 
		}
		result.put("amount", financing.getAmount());
		result.put("term", financing.getTerm());
		result.put("profit_type", financing.getProfitType());
		//产品说明	description
		result.put("description", StringUtils.replaceHtml(StringEscapeUtils.unescapeHtml4(financing.getDescription())));
		//使用期限	time_limit
		result.put("time_limit", financingAttribute.getTimeLimit());
		//服务承诺	Promise
		result.put("promise", StringUtils.replaceHtml(StringEscapeUtils.unescapeHtml4(financingAttribute.getPromise())));
		
        return  result;
    }

}
